<template>
  <div class="xtx-form">
    <div class="user-info">
      <img :src="avatar" alt="" />
      <p>Hi，{{nickname}} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <Form ref="target" :validation-schema="schema" v-slot="{errors}" autocomplete="off">
      <div class="xtx-form-item">
        <div class="field">
          <i class="icon iconfont icon-phone"></i>
          <Field class="input" v-model="formData.mobile" name="mobile" :class="{err:errors.mobile}"
            type="text" placeholder="绑定的手机号" />
        </div>
        <div class="error" v-if="errors.mobile">{{errors.mobile}}</div>
      </div>
      <div class="xtx-form-item">
        <div class="field">
          <i class="icon iconfont icon-code"></i>
          <Field class="input" v-model="formData.code" name="code" :class="{err:errors.code}"
            type="text" placeholder="短信验证码" />
          <span @click="send" class="code"> {{time===0?'发送验证码':`${time}秒后发送`}}</span>
        </div>
        <div class="error" v-if="errors.code">{{errors.code}}</div>
      </div>
    </Form>
    <a @click="submit" href="javascript:;" class="submit">立即绑定</a>
  </div>
</template>

<script>
import { reactive, ref } from 'vue'
import { Form, Field } from 'vee-validate'
import QC from 'qc'
import { mobile, code } from '@/utils/validate'
import { userQQBindCode } from '@/api/user'
import { useCountdown } from '@/compositions/index.js'
import Message from '@/components/Message'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
export default {
  name: 'CallbackBind',
  components: { Form, Field }, // 局部注册
  props: { unionId: { type: String, default: '', required: true } },
  setup (props) {
    const target = ref(null) // 表单引用
    // 定义数据项   qq头像和昵称
    const nickname = ref('')
    const avatar = ref('')
    if (QC.Login.check()) {
      QC.api('get_user_info').success(res => {
        console.log('123456', res)
        avatar.value = res.data.figureurl_qq_2 // 头像
        nickname.value = res.data.nickname // 昵称
      })
    }
    //  定义表单数据对象
    const formData = reactive({
      mobile: '13241051259',
      code: ''
    })
    // 校验规则
    const schema = {
      mobile: mobile,
      code: code
    }
    // 手动兜底校验
    const submit = () => {
      target.value.validate().then(valid => {
        if (valid) {
          console.log('通过校验')
          doBind()
        }
      })
    }
    const store = useStore()
    const router = useRouter()
    const doBind = async () => {
      // 调用actions 做绑定
      try {
        await store.dispatch('user/userQQBindLogin', {
          unionId: props.unionId,
          mobile: formData.mobile,
          code: formData.code
        })
        // 合并购物车
        await store.dispatch('cart/mergeLocalCart')
        Message({ type: 'success', text: '绑定成功' })
        router.push('/')
      } catch (err) {
        Message({ type: 'error', text: '绑定失败' })
      }
    }
    // 发送验证码
    const { time, start } = useCountdown()
    const send = () => {
      // 通过校验才可以发送请求
      const valid = mobile(formData.mobile)
      if (!valid) {
        target.value.setFieldError('mobile', valid)
        return
      }
      if (time.value !== 0) {
        return
      }
      // 发送ajax
      userQQBindCode(formData.mobile).then(data => {
        Message({ type: 'success', text: '验证码已发送,注意查收' })
        start(60)
      }).catch(err => {
        // console.dir(err)
        Message({ type: 'error', text: err.response.data.message })
      })
    }

    return { nickname, avatar, target, formData, schema, submit, send, time, start }
  }
}
</script>

<style scoped lang='less'>
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
